//
//  AnchorViewController.swift
//  七哥直播
//
//  Created by seven on 2017/12/20.
//  Copyright © 2017年 seven. All rights reserved.
//

import UIKit
private let KCellIdentifer = "HomeViewCell"
class AnchorViewController: UIViewController {

    var homeType: HomeType!
    private lazy var homeVM = HomeViewModel()
    
    private lazy var collectionView: UICollectionView = {
        let layout = LxWaterFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 5, left: 10, bottom: 10, right: 10)
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        layout.dataSource = self
        let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = .white
        collectionView.register(UINib(nibName: "HomeViewCell", bundle: nil), forCellWithReuseIdentifier: KCellIdentifer)
        return collectionView
    }()
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        view.addSubview(collectionView)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadData(index: 0)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

//MARK:- collectioinView数据源&&代理
extension AnchorViewController: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return homeVM.anchorModels.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KCellIdentifer, for: indexPath) as! HomeViewCell
        cell.anchorModel = homeVM.anchorModels[indexPath.row]
        if indexPath.row == homeVM.anchorModels.count - 1 {
            loadData(index: homeVM.anchorModels.count)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let roomVc = RoomViewController()
        navigationController?.pushViewController(roomVc, animated: true)
    }
}

//MARK:- 瀑布流数据源
extension AnchorViewController: LxWaterFlowLayoutDataSource{
    func numberOfCols(_ waterfall: LxWaterFlowLayout) -> Int {
        return 2
    }
    func waterfall(_ waterfall: LxWaterFlowLayout, heightForItemAt indexPath: IndexPath) -> CGFloat {
        return indexPath.item % 2 == 0 ? kScreenW * 2 / 3 : kScreenW * 0.5
    }
}

//MARK:- 数据相关
extension AnchorViewController{
    private func loadData(index: Int){
        homeVM.loadHomeData(type: homeType, index: index) {
            self.collectionView.reloadData()
        }
    }
}
